// const fs = require('fs');
// const path = require('path')
// const { default: MagicString } = require('magic-string');
// const Module = require('./module')
import {Bundle as bbbb} from "magic-string";
import path from 'path';
import fs from 'fs';
import Module from './module.js';
export default class Bundle{
  constructor(options){
    this.entryPath = options.entry.replace(/\.js$/,'')+'.js';
    this.modules = {};
    this.deps = [];
  }

  build(outputFileName){
    const entryMoudle = this.fetchModule(this.entryPath);
    //展开
    // Promise.resolve().then(()=>entryMoudle.expandAllStatements()).then(data=>{
      // console.log(data);
    this.startments = entryMoudle.expandAllStatements();
    this.generate(outputFileName);
  
    // this.startments = entryMoudle.expandAllStatements();
    
    
    
  }
  fetchModule(importee,importer){
    let route;
    //如果没有importer 那么就是入口
    //./msg.js e:\web\learn\rollup\src\main.js
    if(!importer){
      route = importee;
    }else{
      if(path.isAbsolute(importee)){
        route = importee
      }else if(importee[0] === '.'){
        route = path.resolve(path.dirname(importer),importee.replace(/\.js$/,'')+'.js')
      }
    }
    if(route){
      let code = fs.readFileSync(route,'utf-8');
      const module = new Module({
        code,
        path:route,
        bundle:this
      });
      this.modules[importee] = module;
      
      return module;
    }
    
  }

  generate(outputFileName1){
    //添加外部依赖
    let magicStringg = new bbbb();
    this.deps.forEach(statement =>{
      magicStringg.addSource({
        content:statement._source,
        separator:'\n'
      })
    })
    this.startments.forEach(statement => {
      const source = statement._source.clone();
      if(statement.type === 'ExportNamedDeclaration'
        && statement.declaration){
        source.remove(statement.start,statement.declaration.start)
      }else if(statement.type === 'ExportDefaultDeclaration' && statement.declaration){
        source.remove(statement.start,statement.declaration.start)
      }
      magicStringg.addSource({
        content:source,
        separator:'\n'
      })
    });
    fs.writeFileSync(outputFileName1,magicStringg.toString(),'utf-8')
  }
}